<template>
  <el-dialog append-to-body :title="$t('product.component.qrcodeDialog.title3')" :visible.sync="visible" top="50px" width="650px">
    <div class="dialog-container create-qrcode">
      <div class="content">
        <el-tabs v-model="activeName" style="height:100%;display: flex;flex-direction: column;">
          <el-tab-pane :label="$t('product.component.qrcodeDialog.qrcode')" name="qrCode" style="height:100%;"></el-tab-pane>
          <el-tab-pane v-if="isOpenMiniProgramCode" :label="$t('product.component.qrcodeDialog.miniProgramCode')" name="miniProgramCode" style="height:100%;"></el-tab-pane>
        </el-tabs>

        <h4>{{$t('product.component.qrcodeDialog.title1')}}</h4>

        <div class="qrcode-wrapper">
          <div class="qrcode-left">
            <p class="qrcode-tip">{{ $t('product.component.qrcodeDialog.text5') }}</p>
            <div class="qrcode-content" ref="qrcodeContent">
              <p class="qrcode-item com-item" v-if="showCompanyName">{{initData.nickName}}</p>
              <div class="code-container qrcode-item" v-show="activeName=='qrCode'">
                <div ref="qrCodeWrap" id="qrCodeWrap"></div>
              </div>
              <div class="code-container qrcode-item" v-show="activeName=='miniProgramCode'">
                <img :src="miniProgramDefaultImg" class="miniProgramCodeImg" alt="">
              </div>
              <p class="qrcode-item">{{getDisplayName('qrcodeId')}}</p>
              <p class="qrcode-item qrcode-item-line" v-if="showLine"></p>
              <p class="qrcode-item" :class="itemClass(item)" v-for="item in checkList" :key="item">
                <template v-if="item === 'qualityInfo'">
                  <p class="qrcode-item qrcode-item-quality">{{ $t('common.form.preview.qualityField.label3') }}：</p>
                  <p class="qrcode-item qrcode-item-quality">{{ $t('common.form.preview.qualityField.label1') }}：</p>
                  <p class="qrcode-item qrcode-item-quality">{{ $t('common.form.preview.qualityField.label2') }}：</p>
                </template>
                <template v-else>
                  {{ getDisplayName(item) }}：
                </template>
              </p>
            </div>
          </div>

          <div class="qrcode-right">
            <h5>
              {{ $t('product.component.qrcodeDialog.title2') }}({{checkList.length}}/5)
              <el-tooltip effect='dark' :content="$t('product.component.qrcodeDialog.tip1')" placement="top">
                <i class="iconfont icon-fdn-info" style="font-size:13px;"></i>
              </el-tooltip>
            </h5>
            <el-checkbox-group class="field-list" @change="checkChange" v-model="checkList">
              <el-checkbox v-for="item in fieldList" :key="item.fieldName" :label="item.fieldName" :disabled='item.disabled'>{{item.displayName}}</el-checkbox>
            </el-checkbox-group>
          </div>
          <div ref="bridge" style="display:none;"></div>
        </div>
      </div>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('common.base.cancel') }}</el-button>
      <el-button type="primary" :disabled="pending" @click="save">{{ $t('common.base.save') }}</el-button>
    </span>

  </el-dialog>
</template>

<script>
import * as productQrcode from '@src/api/productQrcode';
import QRCode from 'qrcodejs2';
import { wechatGetAuthInfo } from '@src/api/DoMyself.js';
import VersionMixin from '@src/mixins/versionMixin/index.ts';
import { getOssUrl } from '@src/util/assets';
import { t } from '@src/locales';

const logoImg = getOssUrl('/productV2/logo.png');

export default {
  name: 'qrcode-style-dialog',
  mixins: [VersionMixin],
  data() {
    return {
      visible: false,
      checkList: [],
      fieldList: [
        { displayName: t('product.component.qrcodeDialog.companyLogo'), fieldName: 'companyLogo' },
        { displayName: t('product.component.qrcodeDialog.companyName'), fieldName: 'companyName' },
      ],
      filterFieldsNameMap: [],
      allFieldsNameMap: [],
      isFirst: false,
      pending: false,
      activeName: 'qrCode',
      isOpenMiniProgramCode: false,
      miniProgramDefaultImg: '', // 生成的时候展示
    };
  },
  computed: {
    hasCompanyLogo() {
      return this.initData.companyLogo;
    },
    showCompanyName() {
      return this.checkList.indexOf('companyName') > -1;
    },
    showLine() {
      let list = this.checkList.slice();
      const index = list.findIndex(item => item !== 'companyName' && item !== 'companyLogo');
      return index > -1;
    },
    defLogo() {
      return logoImg;
    },
    auths() {
      return this.initData?.auths;
    },
  },
  props: {
    initData: {
      type: Object,
      default: () => {},
    },
  },
  mounted() {
    this.getProductFields();
    this.wechatGetAuthInfo();
  },
  methods: {
    // 获取名称
    getDisplayName(fieldName) {
      if (fieldName === 'qrcodeId') {
        return t('product.type.qrcodeId');
      }
      const item = this.fieldList.find(item => item.fieldName === fieldName) || {};
      return item.displayName || '';
    },

    itemClass(fieldName) {
      if (fieldName !== 'qrcodeId' && fieldName !== 'companyName' && fieldName !== 'companyLogo') {
        return 'qrcode-item-center';
      }
      return 'qrcode-item-none';
    },
    // 勾选
    checkChange(val) {
      if (val.length > 5) {
        this.$message.warning(t('product.component.qrcodeDialog.tip3'));
        this.checkList.splice(5);
      } else {
        this.showLogo(!(val.indexOf('companyLogo') < 0));
        localStorage.setItem(`qrcode_check_items_${this.initData.domain}`, this.checkList.join(','));
      }
    },
    // 获取产品自定义字段
    async getProductFields() {
      try {
        let { status, data, message } = await productQrcode.getProductFields({ isFromSetting: false });
        if (status === 0) {
          const filterType = ['autograph', 'select', 'attachment', 'separator', 'info'];
          // 获取到被过滤的字段名称map
          this.filterFieldsNameMap = data
            .map(f => {
              return filterType.includes(f.formType) || f.setting?.isSubForm ? f.fieldName : '';
            })
            .filter(f => f && f.trim());

          data = data.filter(item => !this.filterFieldsNameMap.includes(item.fieldName));
          this.fieldList = this.fieldList.concat(data);
          this.allFieldsNameMap = this.fieldList.map(f => f.fieldName);

          if (!this.hasCompanyLogo) {
            this.fieldList[0].disabled = true;
          }
          this.handleCheckList()
        } else {
          this.$message.error(message);
        }
      } catch (err) {
        console.error(err);
      }
    },
    handleCheckList() {
      const checkFields = localStorage.getItem(`qrcode_check_items_${this.initData.domain}`);
      if (checkFields) {
        // 兼容，历史选中的不能展示的类型需要被清除选中
        this.checkList = checkFields.split(',').filter(f => !this.filterFieldsNameMap.includes(f) && this.allFieldsNameMap.includes(f));
        const logoIndex = this.checkList.findIndex(item => item === 'companyLogo');
        if (logoIndex > -1 && !this.hasCompanyLogo) {
          this.checkList.splice(logoIndex, 1);
        }
      }
    },
    open() {
      this.visible = true;
      if (!document.getElementById('qrCodeWrap')) {
        return setTimeout(() => {
          this.open();
        }, 200);
      }
      this.$nextTick(() => {
        // 预览关联产品的二维码
        this.showQrcode();
        if (!this.isFirst) {
          this.handleCheckList()
        }
        this.isFirst = false
      });
    },

    // 显示二维码
    showQrcode() {
      document.getElementById('qrCodeWrap').innerHTML = '';
      // 初始化生成二维码
      new QRCode(this.$refs.qrCodeWrap, {
        text: `${window.location.origin}/qrcode/${this.initData.domain}?qrcodeId=`, // 需要转换为二维码的内容
        width: 120,
        height: 120,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H,
      });
      // 判断是否展示公司logo
      const isShowLogo = !(this.checkList.indexOf('companyLogo') < 0);
      // 点击生成二维码的时候 第一次未勾选公司logo 展示默认logo
      this.showLogo(isShowLogo, true);
    },

    /**
      * @description: 显示logo
      * @param {Boolean} showLogo 是否展示logo
      * @param {Boolean} showDef 是否展示默认logo
      */
    showLogo(showLogo = true, showDef = false) {
      // 先清空logo img 再append
      const canvasChildNodes = this.$refs.qrCodeWrap?.childNodes || [];
      canvasChildNodes &&
        canvasChildNodes.forEach(childNode => {
          if (childNode.id === 'companyLogo') this.$refs.qrCodeWrap.removeChild(childNode);
        });

      if (!this.hasCompanyLogo) {
        const index = this.checkList.findIndex(item => item === 'companyLogo');
        if (index > -1) this.checkList.splice(index, 1);
        localStorage.setItem(`qrcode_check_items_${this.initData.domain}`, this.checkList.join(','));
      }

      if (!showLogo && !showDef) return;

      this.$nextTick(() => {
        const img = document.createElement('img');
        img.src = !showLogo && showDef ? this.defLogo : this.initData.companyLogo;
        img.setAttribute('id', 'companyLogo');
        img.style.position = 'absolute';
        img.style.top = 'calc(50% - 18px)';
        img.style.left = 'calc(50% - 18px)';
        img.style.width = '36px';
        img.style.height = '36px';
        img.style.border = '2px solid #fff';
        img.style.borderRadius = '4px';
        img.style.backgroundColor = '#fff';
        this.$refs.qrCodeWrap.appendChild(img);
      });
    },
    // 获取授权信息-小程序
    async wechatGetAuthInfo() {
      const { data } = await wechatGetAuthInfo();
      if (data && data.status == 1) {
        this.isOpenMiniProgramCode = !!data.data.attribute.appletQrcodeStatus;
        this.miniProgramDefaultImg = data.data.attribute.qrCodeOssUrl;
      }
    },
    save() {
      this.$emit('checkList', this.checkList);
      this.visible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog-container {
  &.create-qrcode {
    padding-left: 30px;
  }
  .content {
    padding: 10px 20px;
  }
}
::v-deep .el-checkbox {
  margin-bottom: 4px;
}
::v-deep .el-checkbox__label {
  color: #606266 !important;
}
::v-deep .el-dialog {
  border-radius: 8px;
}
::v-deep .el-dialog__header {
  background-color: $bg-color-l2;
  padding-top: 10px;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  font-weight: bold;

  .el-dialog__headerbtn {
    top: 0;
  }
}
::v-deep .el-dialog__body {
  padding: 0;
}
::v-deep .el-dialog__footer {
  border-top: 1px solid $color-border-l2;
  padding-bottom: 10px;
}
#qrCodeWrap {
  position: relative;
}
.download-top {
  padding-left: 20px;
  background-color: #fffbe4;
  color: #f2cd79;
  width: 100%;
  height: 30px;
  line-height: 30px;
}
.qrcode-wrapper {
  display: flex;
  justify-content: space-between;
  padding: 12px;
  background-color: $bg-color-l1;
  border-radius: 4px;

  .qrcode-left {
    width: 350px;

    .qrcode-tip {
      font-size: 12px;
      margin-bottom: 10px;
    }

    .qrcode-content {
      // border: 1px solid $color-border-l1;
      padding-bottom: 10px;
      min-height: 290px;
      background-color: #fff;
      padding-top: 2px;

      .qrcode-company {
        text-align: center;
        margin: 20px;
      }
      .qrcode-item {
        text-align: center;
        margin: 5px 0;
        font-size: 12px;
        .miniProgramCodeImg {
          width: 120px;
          height: 120px;
        }
      }
      .com-item {
        margin-top: 12px;
      }
      .qrcode-item-center {
        text-align: left;
        margin-left: 20px;
        margin-top: 5px;
      }
      .qrcode-item-none {
        display: none;
      }
      .qrcode-item-line {
        height: 0;
        border-bottom: 1px dashed $color-border-l1;
      }
      .qrcode-item-quality {
        text-align: left;
        margin-top: 5px;
      }
      .code-container {
        border: 1px solid $color-border-l1;
        border-radius: 10px;
        padding: 5px;
        width: 130px;
        height: 130px;
        margin: 10px auto;

        div {
          height: 110px;
        }
      }
    }
  }
  .qrcode-right {
    width: 34%;
    max-height: 316px;

    .field-list {
      height: calc(100% - 30px);
      overflow-y: auto;
      display: flex;
      flex-direction: column;
    }
  }
}
.qrcode-bottom {
  margin-top: 20px;

  .qrcode-create-num {
    display: flex;
    align-items: baseline;

    ::v-deep .el-input {
      width: 100px;
      margin-right: 10px;
    }
    .qrcode-margin {
      color: $color-warning;
    }
  }
  .qrcode-text {
    margin-top: 15px;
    span {
      color: $color-warning;
    }
  }
}
.stepper {
  position: absolute;
  top: 104px;
  left: 15px;
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  align-items: center;

  div {
    width: 26px;
    height: 26px;
    font-size: 16px;
    color: #fff;
    background-color: $color-primary;
    border-radius: 50%;
    text-align: center;
    line-height: 24px;
  }
  p {
    width: 0;
    border-left: 2px solid $color-border-l1;
    margin-bottom: 0;
    height: 360px;
  }
}
</style>